package com.example.demo.zaqizabatest.多线程相关;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName 取钱
 * @Author lys4134
 * @Date 2021/08/27 10:01:18
 * @Description 取钱 2.两个人AB通过一个账户A在柜台取钱和B在ATM机取钱！
 * @Version 1.0
 **/
@SuppressWarnings({"AlibabaLowerCamelCaseVariableNaming", "AlibabaAvoidManuallyCreateThread"})
public class 取钱 {
    // 假设一个账户有1000块钱
    static double money = 1000;
    // 柜台Counter取钱的方法
    private static void Counter(double money1) throws InterruptedException {
        money -= money1;
        System.out.println(Thread.currentThread().getName() + "在柜台取钱" + money1 + "元，还剩" + money + "元！");
        Thread.sleep(1000);
    }
    // ATM取钱的方法
    private static void  ATM(double money1) throws InterruptedException {
        money -= money1;
        System.out.println(Thread.currentThread().getName() + "在ATM取钱" + money1 + "元，还剩" + money + "元！");
        Thread.sleep(1000);
    }

    //提供一个对外取款途径，防止直接调取方法同时取款时，并发余额显示错误
    public static synchronized void outMoney(double money1, String mode) throws Exception{

            if(money1 > money){
                //校验余额是否充足
                throw new Exception("取款金额"+money1+",余额只剩"+money+"，取款失败");
            }
            if("ATM".equals(mode)){
                ATM(money1);
            } else {
                Counter(money1);
            }

    }

    public static void main(String[] args) throws Exception {
        List<Thread> threads = new ArrayList<>();
        threads.add(new Thread(() -> {
            try {
                while (money > 200){

                    outMoney(100, "ATM");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "A"));
        threads.add(new Thread(() -> {
            try {
                while (money > 200){

                    outMoney(200, "柜台");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "B"));
        for (Thread thread : threads){
            thread.start();
        }


//        new Thread(() -> {
//            try {
//                outMoney(10, "aaa");
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }, Thread.currentThread().getName() + 1).start();
//        outMoney(100, "ATM");

    }

}
